#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

void CheckCapacity(SeqList* ps)
{
	if (ps->capacity == ps->size)
	{
		SLDateType* temp = (SLDateType*)realloc(ps->data, sizeof(SLDateType) * 2 * (ps->capacity));
		if (temp == NULL)
		{
			perror("realloc");
			exit(-1);
		}
		ps->data = temp;
		ps->capacity = 2 * ps->capacity;
	}
}

void SeqListPrint(SeqList* ps)
{
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->data[i]);
	}
}


void SeqListInit(SeqList* ps)
{
	SLDateType* pa = (SLDateType*)malloc(sizeof(SLDateType) * 4);
	if (pa == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	ps->capacity = 4;
	ps->size = 0;
	ps->data = pa;
}
void SeqListDestroy(SeqList* ps)
{
	free(ps->data);
	ps->data = NULL;
	ps->capacity = 0;
	ps->size = 0;
}

void SeqListPushBack(SeqList* ps, SLDateType x)
{
	SeqListInsert(ps, ps->size, x);
	
}

void SeqListPopBack(SeqList* ps)
{
	assert(ps);
	/*if (ps->size == 0)
		return;
	ps->size--;*/
	SeqListErase(ps, ps->size - 1);
}


void SeqListPushFront(SeqList* ps, SLDateType x)
{
	SeqListInsert(ps, 0, x);
	CheckCapacity(ps);
	//if (ps->size == 0)
	//{
	//	ps->data[ps->size] = x;
	//	ps->size++;
	//}
	//else
	//{
	//	// 数据向后移动
	//	int move = ps->size - 1;
	//	while (move >= 0)
	//	{
	//		ps->data[move + 1] = ps->data[move];
	//		move--;
	//	}
	//	ps->data[0] = x;
	//	ps->size++;

	//}
}

void SeqListPopFront(SeqList* ps)
{
	/*if (ps->size == 0)
		return;
	int move = 0;
	for (move = 0; move < ps->size - 1; move++)
	{
		ps->data[move] = ps->data[move + 1];
	}
	ps->size--;*/
	SeqListErase(ps, 0);

}

int SeqListFind(SeqList* ps, SLDateType x)
{
	int move = 0;
	for (move = 0; move < ps->size; move++)
	{
		if (ps->data[move] == x)
			return move;  // 返回目标元素的下标
	}
	return -1;
}


void SeqListInsert(SeqList* ps, int pos, SLDateType x)
{
	if (ps->size == 0)
	{
		ps->data[ps->size] = x;
		ps->size++;
		return;
	}

	assert(pos >= 0 && pos <= ps->size);
	CheckCapacity(ps);
	
	if (pos == ps->size)
	{
		ps->data[ps->size] = x;
		ps->size++;
	}
	else
	{

		// 数据向后移动
		int move = ps->size - 1;
		while (move >= pos)
		{
			ps->data[move + 1] = ps->data[move];
			move--;
		}
		ps->data[pos] = x;
		ps->size++;
	}
}

void SeqListErase(SeqList* ps, int pos)
{
	assert(pos >= 0 && pos < ps->size);
	if (ps->size == 0)
		return;
	if (pos == ps->size - 1)
		ps->size--;
	else
	{
		int move = pos;
		for (move = pos; move < ps->size - 1; move++)
		{
			ps->data[move] = ps->data[move + 1];
		}
		ps->size--;
	}
}
